------------------------------------------------------------------------------
-- Logging api for computercraft by Hea3veN
-- Version 0.2
------------------------------------------------------------------------------

Levels = {
	ERROR=1,
	WARNING=2,
	INFO=3,
	DEBUG=4,
	[1]=1,
	[2]=2,
	[3]=3,
	[4]=4
}
LevelName = {
	[1]="ERROR",
	[2]="WARNING",
	[3]="INFO",
	[4]="DEBUG"
}
ERROR = Levels['ERROR']
WARNING = Levels['WARNING']
INFO = Levels['INFO']
DEBUG = Levels['DEBUG']

Level = DEBUG

LogToFile = true
LogToConsole = true

LogFileMaxSize = 128 * 1024

LogDir = '/var/log'
LogFileName = 'out.log'

OnLog = nil

function logf(level, module, fmt, ...)
	if Levels[level] == nil or Level < Levels[level] then
		return
	end

	local logMsg = string.format(fmt, ...)
	logString = string.format('%s %s [%s] %s: %s', textutils.formatTime(os.time(), true), os.getComputerLabel(), LevelName[Levels[level]], module, logMsg)
	
	if LogToConsole then
		print(string.format('[%s] %s: %s', LevelName[Levels[level]], module, logMsg))
	end
	
	if LogToFile then
		if not fs.exists(LogDir) then
			fs.makeDir(LogDir)
		end
		local logPath = LogDir..'/'..LogFileName
		if fs.exists(logPath) and fs.getSize(logPath) >= LogFileMaxSize then
			fs.delete(logPath..'.1')
			fs.move(logPath, logPath..'.1')
		end
		local mode = nil
		if fs.exists(logPath) then
			mode = 'a'
		else
			mode = 'w'
		end
		local f = fs.open(logPath, mode)
		
		f.write(logString..'\n')
		f.close()
		
		if logfOnLog ~= nil then
			logfOnLog(level, module, logMsg)
		end
	end
end

function setLogToConsole(val)
	LogToConsole = val
end
